package com.njmd.mdbs.web.service.impl;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.njmd.framework.base.BaseCrudServiceImpl;
import com.njmd.framework.dao.BaseHibernateDAO;
import com.njmd.mdbs.web.dao.SysLoginRoleDAO;
import com.njmd.mdbs.web.dao.SysPermissionDAO;
import com.njmd.mdbs.web.entity.sys.SysLogin;
import com.njmd.mdbs.web.entity.sys.SysLoginRole;
import com.njmd.mdbs.web.entity.sys.SysPermission;
import com.njmd.mdbs.web.service.SysLoginService;
import com.njmd.mdbs.web.service.SysRolePermissionService;

/**
 * 用户管理
 * 
 * @author sunqw
 * @since 2013.10.12
 */
@Service
public class SysLoginServiceImpl extends BaseCrudServiceImpl<SysLogin, Long> implements SysLoginService
{
	@Autowired
	private SysLoginRoleDAO sysLoginRoleDAO;
	@Autowired
	private SysRolePermissionService sysRolePermissionService;
	@Autowired
	private SysPermissionDAO sysPermissionDAO;

	@Override
	@Autowired
	@Qualifier(value = "sysLoginDao")
	public void setBaseDao(BaseHibernateDAO<SysLogin, Long> baseDao)
	{
		this.baseDao = baseDao;
	}

	@Override
	public SysLogin findByLoginName(String loginName) throws Exception
	{
		return this.baseDao.findUnique("loginName", loginName);
	}

	@Override
	public Set<String> findPermissionsByLogin(SysLogin login) throws Exception
	{
		Set<String> result = Sets.newHashSet();
		List<SysPermission> permissionList = Lists.newArrayList();

		// 超级管理员
		if (login.isSuperAdmin())
		{
			permissionList = sysPermissionDAO.findBySystemId(login.getSystemId());
		}
		// 普通人员
		else
		{
			List<SysLoginRole> roleList = sysLoginRoleDAO.findByLoginId(login.getLoginId());

			if (roleList == null || roleList.isEmpty())
			{
				return Sets.newHashSet();
			}
			else
			{
				int size = roleList.size();
				Long[] roleIds = new Long[size];
				for (int i = 0; i < size; i++)
				{
					roleIds[i] = roleList.get(i).getSysRole().getRoleId();
				}
				permissionList = sysRolePermissionService.findByRoleIds(roleIds);

			}
		}
		if (permissionList.isEmpty())
		{
			return Sets.newHashSet();
		}
		for(SysPermission sysPermission : permissionList)
		{
			result.add(sysPermission.getPermissionKey());
		}
		return result;
	}

}
